home *** CD-ROM | disk | FTP | other *** search
/ FishMarket 1.0 / FishMarket v1.0.iso / fishies / 051-075 / disk_061 / microemacs / isearch.c < prev    next >
C/C++ Source or Header  |  1992-05-06  |  19KB  |  508 lines

  1. /*
  2.  * The functions in this file implement commands that perform incremental
  3.  * searches in the forward and backward directions.  This "ISearch" command
  4.  * is intended to emulate the same command from the original EMACS 
  5.  * implementation (ITS).  Contains references to routines internal to
  6.  * SEARCH.C.
  7.  *
  8.  * REVISION HISTORY:
  9.  *
  10.  *    D. R. Banks 9-May-86
  11.  *    - added ITS EMACSlike ISearch
  12.  *
  13.  *    John M. Gamble 5-Oct-86
  14.  *    - Made iterative search use search.c's scanner() routine.
  15.  *      This allowed the elimination of bakscan().
  16.  *    - Put isearch constants into esearch.h
  17.  *    - Eliminated the passing of 'status' to scanmore() and
  18.  *      checknext(), since there were no circumstances where
  19.  *      it ever equalled FALSE.
  20.  */
  21.  
  22. #include        <stdio.h>
  23. #include    "estruct.h"
  24. #include        "edef.h"
  25. #include    "esearch.h"
  26.  
  27. #if    ISRCH
  28.  
  29. extern int scanner();            /* Handy search routine */
  30. extern int eq();            /* Compare chars, match case */
  31. extern char tap[];            /* Reverse pattern array.*/
  32. /* A couple of "own" variables for re-eat */
  33.  
  34. int    (*saved_get_char)();        /* Get character routine */
  35. int    eaten_char = -1;        /* Re-eaten char */
  36.  
  37. /* A couple more "own" variables for the command string */
  38.  
  39. int    cmd_buff[CMDBUFLEN];        /* Save the command args here */
  40. int    cmd_offset;            /* Current offset into command buff */
  41. int    cmd_reexecute = -1;        /* > 0 if re-executing command */
  42.  
  43.  
  44. /*
  45.  * Subroutine to do incremental reverse search.  It actually uses the
  46.  * same code as the normal incremental search, as both can go both ways.
  47.  */
  48.  
  49. int risearch(f, n)
  50. {
  51.     LINE *curline;            /* Current line on entry          */
  52.     int  curoff;            /* Current offset on entry          */
  53.  
  54.     /* remember the initial . on entry: */
  55.  
  56.     curline = curwp->w_dotp;        /* Save the current line pointer      */
  57.     curoff  = curwp->w_doto;        /* Save the current offset          */
  58.  
  59.     /* Make sure the search doesn't match where we already are:              */
  60.  
  61.     backchar(TRUE, 1);            /* Back up a character              */
  62.  
  63.     if (!(isearch(f, -n)))        /* Call ISearch backwards          */
  64.     {                    /* If error in search:              */
  65.     curwp->w_dotp = curline;    /* Reset the line pointer          */
  66.     curwp->w_doto = curoff;        /*  and the offset to original value  */
  67.     curwp->w_flag |= WFMOVE;    /* Say we've moved              */
  68.     update(FALSE);            /* And force an update              */
  69.     mlwrite ("[search failed]");    /* Say we died                  */
  70.     } else mlerase ();            /* If happy, just erase the cmd line  */
  71. }
  72.  
  73. /* Again, but for the forward direction */
  74.  
  75. int fisearch(f, n)
  76. {
  77.     LINE *curline;            /* Current line on entry          */
  78.     int  curoff;            /* Current offset on entry          */
  79.  
  80.     /* remember the initial . on entry: */
  81.  
  82.     curline = curwp->w_dotp;        /* Save the current line pointer      */
  83.     curoff  = curwp->w_doto;        /* Save the current offset          */
  84.  
  85.     /* do the search */
  86.  
  87.     if (!(isearch(f, n)))        /* Call ISearch forwards          */
  88.     {                    /* If error in search:              */
  89.     curwp->w_dotp = curline;    /* Reset the line pointer          */
  90.     curwp->w_doto = curoff;        /*  and the offset to original value  */
  91.     curwp->w_flag |= WFMOVE;    /* Say we've moved              */
  92.     update(FALSE);            /* And force an update              */
  93.     mlwrite ("[search failed]");    /* Say we died                  */
  94.     } else mlerase ();            /* If happy, just erase the cmd line  */
  95. }
  96.  
  97. /*
  98.  * Subroutine to do an incremental search.  In general, this works similarly
  99.  * to the older micro-emacs search function, except that the search happens
  100.  * as each character is typed, with the screen and cursor updated with each
  101.  * new search character.
  102.  *
  103.  * While searching forward, each successive character will leave the cursor
  104.  * at the end of the entire matched string.  Typing a Control-S or Control-X
  105.  * will cause the next occurrence of the string to be searched for (where the
  106.  * next occurrence does NOT overlap the current occurrence).  A Control-R will
  107.  * change to a backwards search, META will terminate the search and Control-G
  108.  * will abort the search.  Rubout will back up to the previous match of the
  109.  * string, or if the starting point is reached first, it will delete the
  110.  * last character from the search string.
  111.  *
  112.  * While searching backward, each successive character will leave the cursor
  113.  * at the beginning of the matched string.  Typing a Control-R will search
  114.  * backward for the next occurrence of the string.  Control-S or Control-X
  115.  * will revert the search to the forward direction.  In general, the reverse
  116.  * incremental search is just like the forward incremental search inverted.
  117.  *
  118.  * In all cases, if the search fails, the user will be feeped, and the search
  119.  * will stall until the pattern string is edited back into something that
  120.  * exists (or until the search is aborted).
  121.  */
  122.  
  123. isearch(f, n)
  124. {
  125.     int            status;        /* Search status */
  126.     int            col;        /* prompt column */
  127.     register int    cpos;        /* character number in search string  */
  128.     register int    c;        /* current input character */
  129.     register int    expc;        /* function expanded input char          */
  130.     char        pat_save[NPAT];    /* Saved copy of the old pattern str  */
  131.     LINE        *curline;    /* Current line on entry          */
  132.     int            curoff;        /* Current offset on entry          */
  133.     int            init_direction;    /* The initial search direction          */
  134.  
  135.     /* Initialize starting conditions */
  136.  
  137.     cmd_reexecute = -1;        /* We're not re-executing (yet?)      */
  138.     cmd_offset = 0;            /* Start at the beginning of the buff */
  139.     cmd_buff[0] = '\0';        /* Init the command buffer          */
  140.     strncpy (pat_save, pat, NPAT);    /* Save the old pattern string          */
  141.     curline = curwp->w_dotp;        /* Save the current line pointer      */
  142.     curoff  = curwp->w_doto;        /* Save the current offset          */
  143.     init_direction = n;            /* Save the initial search direction  */
  144.  
  145.     /* This is a good place to start a re-execution: */
  146.  
  147. start_over:
  148.  
  149.     /* ask the user for the text of a pattern */
  150.     col = promptpattern("ISearch: ");        /* Prompt, remember the col   */
  151.  
  152.     cpos = 0;                    /* Start afresh              */
  153.     status = TRUE;                /* Assume everything's cool   */
  154.  
  155.     /*
  156.        Get the first character in the pattern.  If we get an initial Control-S
  157.        or Control-R, re-use the old search string and find the first occurrence
  158.      */
  159.  
  160.     c = ectoc(expc = get_char());        /* Get the first character    */
  161.     if ((c == IS_FORWARD) ||
  162.         (c == IS_REVERSE) ||
  163.         (c == IS_VMSFORW))            /* Reuse old search string?   */
  164.     {
  165.         for (cpos = 0; pat[cpos] != 0; cpos++)    /* Yup, find the length          */
  166.             col = echochar(pat[cpos],col);    /*  and re-echo the string    */
  167.     if (c == IS_REVERSE) {            /* forward search?          */
  168.         n = -1;                /* No, search in reverse      */
  169.         backchar (TRUE, 1);            /* Be defensive about EOB     */
  170.     } else
  171.         n = 1;                /* Yes, search forward          */
  172.     status = scanmore(pat, n);        /* Do the search          */
  173.     c = ectoc(expc = get_char());        /* Get another character      */
  174.     }
  175.  
  176.     /* Top of the per character loop */
  177.             
  178.     for (;;)                    /* ISearch per character loop */
  179.     {
  180.     /* Check for special characters first: */
  181.     /* Most cases here change the search */
  182.  
  183.     if (expc == metac)            /* Want to quit searching?    */
  184.         return (TRUE);            /* Quit searching now          */
  185.  
  186.     switch (c)                /* dispatch on the input char */
  187.     {
  188.       case IS_ABORT:            /* If abort search request    */
  189.         return(FALSE);            /* Quit searching again          */
  190.  
  191.       case IS_REVERSE:            /* If backward search          */
  192.       case IS_FORWARD:            /* If forward search          */
  193.       case IS_VMSFORW:            /*  of either flavor          */
  194.         if (c == IS_REVERSE)        /* If reverse search          */
  195.         n = -1;                /* Set the reverse direction  */
  196.         else                /* Otherwise,               */
  197.         n = 1;                /*  go forward              */
  198.         status = scanmore(pat, n);        /* Start the search again     */
  199.         c = ectoc(expc = get_char());    /* Get the next char          */
  200.         continue;                /* Go continue with the search*/
  201.  
  202.       case IS_NEWLINE:            /* Carriage return          */
  203.         c = '\n';                /* Make it a new line          */
  204.         break;                /* Make sure we use it          */
  205.  
  206.       case IS_QUOTE:            /* Quote character          */
  207.       case IS_VMSQUOTE:            /*  of either variety          */
  208.         c = ectoc(expc = get_char());    /* Get the next char          */
  209.  
  210.       case IS_TAB:                /* Generically allowed          */
  211.       case '\n':                /*  controlled characters     */
  212.         break;                /* Make sure we use it          */
  213.  
  214.       case IS_BACKSP:            /* If a backspace:            */
  215.       case IS_RUBOUT:            /*  or if a Rubout:          */
  216.         if (cmd_offset <= 1)        /* Anything to delete?          */
  217.         return (TRUE);            /* No, just exit          */
  218.         --cmd_offset;            /* Back up over the Rubout    */
  219.         cmd_buff[--cmd_offset] = '\0';    /* Yes, delete last char   */
  220.         curwp->w_dotp = curline;        /* Reset the line pointer     */
  221.         curwp->w_doto = curoff;        /*  and the offset          */
  222.         n = init_direction;            /* Reset the search direction */
  223.         strncpy (pat, pat_save, NPAT);    /* Restore the old search str */
  224.         cmd_reexecute = 0;            /* Start the whole mess over  */
  225.         goto start_over;            /* Let it take care of itself */
  226.  
  227.       /* Presumably a quasi-normal character comes here */
  228.  
  229.       default:                /* All other chars              */
  230.         if (c < ' ')            /* Is it printable?          */
  231.         {                    /* Nope.              */
  232.         reeat (c);            /* Re-eat the char          */
  233.         return (TRUE);            /* And return the last status */
  234.         }
  235.     }  /* Switch */
  236.  
  237.     /* I guess we got something to search for, so search for it          */
  238.  
  239.     pat[cpos++] = c;            /* put the char in the buffer */
  240.     if (cpos >= NPAT)            /* too many chars in string?  */
  241.     {                    /* Yup.  Complain about it    */
  242.         mlwrite("? Search string too long");
  243.         return(TRUE);            /* Return an error          */
  244.     }
  245.     pat[cpos] = 0;                /* null terminate the buffer  */
  246.     col = echochar(c,col);            /* Echo the character          */
  247.     if (!status) {                /* If we lost last time          */
  248.         TTputc(BELL);        /* Feep again              */
  249.         TTflush();            /* see that the feep feeps    */
  250.     } else                    /* Otherwise, we must have won*/
  251.         if (!(status = checknext(c, pat, n))) /* See if match          */
  252.         status = scanmore(pat, n);    /*  or find the next match    */
  253.     c = ectoc(expc = get_char());        /* Get the next char          */
  254.     } /* for {;;} */
  255. }
  256.  
  257. /*
  258.  * Trivial routine to insure that the next character in the search string is
  259.  * still true to whatever we're pointing to in the buffer.  This routine will
  260.  * not attempt to move the "point" if the match fails, although it will 
  261.  * implicitly move the "point" if we're forward searching, and find a match,
  262.  * since that's the way forward isearch works.
  263.  *
  264.  * If the compare fails, we return FALSE and assume the caller will call
  265.  * scanmore or something.
  266.  */
  267.  
  268. int checknext (chr, patrn, dir)    /* Check next character in search string */
  269. char    chr;            /* Next char to look for         */
  270. char    *patrn;            /* The entire search string (incl chr)   */
  271. int    dir;            /* Search direction             */
  272. {
  273.     register LINE *curline;        /* current line during scan          */
  274.     register int curoff;        /* position within current line          */
  275.     register int buffchar;        /* character at current position      */
  276.     int status;                /* how well things go              */
  277.  
  278.  
  279.     /* setup the local scan pointer to current "." */
  280.  
  281.     curline = curwp->w_dotp;        /* Get the current line structure     */
  282.     curoff  = curwp->w_doto;        /* Get the offset within that line    */
  283.  
  284.     if (dir > 0)            /* If searching forward              */
  285.     {
  286.         if (curoff == llength(curline)) /* If at end of line              */
  287.         {
  288.         curline = lforw(curline);    /* Skip to the next line          */
  289.         if (curline == curbp->b_linep)
  290.         return (FALSE);        /* Abort if at end of buffer          */
  291.         curoff = 0;            /* Start at the beginning of the line */
  292.         buffchar = '\n';        /* And say the next char is NL          */
  293.     } else
  294.         buffchar = lgetc(curline, curoff++); /* Get the next char          */
  295.     if (status = eq(buffchar, chr))    /* Is it what we're looking for?      */
  296.     {
  297.         curwp->w_dotp = curline;    /* Yes, set the buffer's point          */
  298.         curwp->w_doto = curoff;    /*  to the matched character          */
  299.         curwp->w_flag |= WFMOVE;    /* Say that we've moved              */
  300.     }
  301.     return (status);        /* And return the status          */
  302.     } else                /* Else, if reverse search:          */
  303.     return (match_pat (patrn));    /* See if we're in the right place    */
  304. }
  305.  
  306. /*
  307.  * This hack will search for the next occurrence of <pat> in the buffer, either
  308.  * forward or backward.  It is called with the status of the prior search
  309.  * attempt, so that it knows not to bother if it didn't work last time.  If
  310.  * we can't find any more matches, "point" is left where it was before.  If
  311.  * we do find a match, "point" will be at the end of the matched string for
  312.  * forward searches and at the beginning of the matched string for reverse
  313.  * searches.
  314.  */
  315.  
  316. int scanmore(patrn, dir)    /* search forward or back for a pattern          */
  317. char    *patrn;            /* string to scan for                  */
  318. int    dir;            /* direction to search                  */
  319. {
  320.     int    sts;            /* search status              */
  321.  
  322.         if (dir < 0)                /* reverse search?          */
  323.         {
  324.         rvstrcpy(tap, patrn);        /* Put reversed string in tap */
  325.         sts = scanner(tap, REVERSE, PTBEG);
  326.     }
  327.     else
  328.         sts = scanner(patrn, FORWARD, PTEND);    /* Nope. Go forward   */
  329.  
  330.     if (!sts)
  331.     {
  332.         TTputc(BELL);    /* Feep if search fails       */
  333.         TTflush();        /* see that the feep feeps    */
  334.     }
  335.  
  336.     return(sts);                /* else, don't even try          */
  337. }
  338.  
  339. /*
  340.  * The following is a worker subroutine used by the reverse search.  It
  341.  * compares the pattern string with the characters at "." for equality. If
  342.  * any characters mismatch, it will return FALSE.
  343.  *
  344.  * This isn't used for forward searches, because forward searches leave "."
  345.  * at the end of the search string (instead of in front), so all that needs to
  346.  * be done is match the last char input.
  347.  */
  348.  
  349. int match_pat (patrn)    /* See if the pattern string matches string at "."   */
  350. char    *patrn;        /* String to match to buffer                 */
  351. {
  352.     register int  i;            /* Generic loop index/offset          */
  353.     register int buffchar;        /* character at current position      */
  354.     register LINE *curline;        /* current line during scan          */
  355.     register int curoff;        /* position within current line          */
  356.  
  357.     /* setup the local scan pointer to current "." */
  358.  
  359.     curline = curwp->w_dotp;        /* Get the current line structure     */
  360.     curoff  = curwp->w_doto;        /* Get the offset within that line    */
  361.  
  362.     /* top of per character compare loop: */
  363.  
  364.     for (i = 0; i < strlen(patrn); i++)    /* Loop for all characters in patrn   */
  365.     {
  366.         if (curoff == llength(curline)) /* If at end of line              */
  367.         {
  368.         curline = lforw(curline);    /* Skip to the next line          */
  369.         curoff = 0;            /* Start at the beginning of the line */
  370.         if (curline == curbp->b_linep)
  371.         return (FALSE);        /* Abort if at end of buffer          */
  372.         buffchar = '\n';        /* And say the next char is NL          */
  373.     } else
  374.         buffchar = lgetc(curline, curoff++); /* Get the next char          */
  375.     if (!eq(buffchar, patrn[i]))    /* Is it what we're looking for?      */
  376.         return (FALSE);        /* Nope, just punt it then          */
  377.     }
  378.     return (TRUE);            /* Everything matched? Let's celebrate*/
  379. }
  380.  
  381. /* Routine to prompt for I-Search string. */
  382.  
  383. int promptpattern(prompt)
  384. char *prompt;
  385. {
  386.     char tpat[NPAT+20];
  387.  
  388.     strcpy(tpat, prompt);        /* copy prompt to output string */
  389.     strcat(tpat, " [");            /* build new prompt string */
  390.     expandp(pat, &tpat[strlen(tpat)], NPAT/2);    /* add old pattern */
  391.     strcat(tpat, "]<META>: ");
  392.  
  393.     /* check to see if we are executing a command line */
  394.     if (!clexec) {
  395.     mlwrite(tpat);
  396.     }
  397.     return(strlen(tpat));
  398. }
  399.  
  400. /* routine to echo i-search characters */
  401.  
  402. int echochar(c,col)
  403. int    c;    /* character to be echoed */
  404. int    col;    /* column to be echoed in */
  405. {
  406.     movecursor(term.t_nrow,col);        /* Position the cursor          */
  407.     if ((c < ' ') || (c == 0x7F))        /* Control character?          */
  408.     {
  409.     switch (c)                /* Yes, dispatch special cases*/
  410.     {
  411.       case '\n':                /* Newline              */
  412.         TTputc('<');
  413.         TTputc('N');
  414.         TTputc('L');
  415.         TTputc('>');
  416.         col += 3;
  417.         break;
  418.  
  419.       case '\t':                /* Tab                  */
  420.         TTputc('<');
  421.         TTputc('T');
  422.         TTputc('A');
  423.         TTputc('B');
  424.         TTputc('>');
  425.         col += 4;
  426.         break;
  427.  
  428.       case 0x7F:                /* Rubout:              */
  429.         TTputc('^');        /* Output a funny looking     */
  430.         TTputc('?');        /*  indication of Rubout      */
  431.         col++;                /* Count the extra char       */
  432.         break;
  433.  
  434.       default:                /* Vanilla control char       */
  435.         TTputc('^');        /* Yes, output prefix          */
  436.             TTputc(c+0x40);        /* Make it "^X"              */
  437.         col++;                /* Count this char          */
  438.     }
  439.     } else
  440.     TTputc(c);            /* Otherwise, output raw char */
  441.     TTflush();                /* Flush the output          */
  442.     return(++col);                /* return the new column no   */
  443. }
  444.  
  445. /*
  446.  * Routine to get the next character from the input stream.  If we're reading
  447.  * from the real terminal, force a screen update before we get the char. 
  448.  * Otherwise, we must be re-executing the command string, so just return the
  449.  * next character.
  450.  */
  451.  
  452. int get_char ()
  453. {
  454.     int    c;                /* A place to get a character          */
  455.  
  456.     /* See if we're re-executing: */
  457.  
  458.     if (cmd_reexecute >= 0)        /* Is there an offset?              */
  459.     if ((c = cmd_buff[cmd_reexecute++]) != 0)
  460.         return (c);            /* Yes, return any character          */
  461.  
  462.     /* We're not re-executing (or aren't any more).  Try for a real char      */
  463.  
  464.     cmd_reexecute = -1;        /* Say we're in real mode again          */
  465.     update(FALSE);            /* Pretty up the screen              */
  466.     if (cmd_offset >= CMDBUFLEN-1)    /* If we're getting too big ...          */
  467.     {
  468.     mlwrite ("? command too long");    /* Complain loudly and bitterly          */
  469.     return (metac);            /* And force a quit              */
  470.     }
  471.     c = get1key();        /* Get the next character          */
  472.     cmd_buff[cmd_offset++] = c; /* Save the char for next time        */
  473.     cmd_buff[cmd_offset] = '\0';/* And terminate the buffer          */
  474.     return (c);                /* Return the character              */
  475. }
  476.  
  477. /*
  478.  * Hacky routine to re-eat a character.  This will save the character to be
  479.  * re-eaten by redirecting the input call to a routine here.  Hack, etc.
  480.  */
  481.  
  482. /* Come here on the next term.t_getchar call: */
  483.  
  484. int uneat()
  485. {
  486.     int c;
  487.  
  488.     term.t_getchar = saved_get_char;    /* restore the routine address          */
  489.     c = eaten_char;            /* Get the re-eaten char          */
  490.     eaten_char = -1;            /* Clear the old char              */
  491.     return(c);                /* and return the last char          */
  492. }
  493.  
  494. int reeat(c)
  495. int    c;
  496. {
  497.     if (eaten_char != -1)        /* If we've already been here          */
  498.     return (NULL);            /* Don't do it again              */
  499.     eaten_char = c;            /* Else, save the char for later      */
  500.     saved_get_char = term.t_getchar;    /* Save the char get routine          */
  501.     term.t_getchar = uneat;        /* Replace it with ours              */
  502. }
  503. #else
  504. isearch()
  505. {
  506. }
  507. #endif
  508.